﻿//	Copyright (c) 2012 Jonathan Loe
//
//	MIT license (http://en.wikipedia.org/wiki/MIT_License)
//
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights 
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
//	of the Software, and to permit persons to whom the Software is furnished to do so, 
//	subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in all 
//	copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
//	INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
//	PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE 
//	FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
//	ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Text;
using System.Transactions;

using Ordinaire.Db;
using Ordinaire.Security.Data;

namespace Ordinaire.Security
{
    /// <summary>
    /// Provides user authentication against database.
    /// </summary>
    public class DbAuthentication : DataAccessEntity, IAuthentication
    {
        /// <summary>
        /// Verifies the specified username and password exist and match.
        /// </summary>
        /// <param name="username">the username to verified</param>
        /// <param name="password">the password of the specified username</param>
        /// <returns>data if both username and password are correct, else null</returns>
        public UserData Authenticate(string username, string password)
        {
            if (String.IsNullOrEmpty(username))
            {
                throw new ArgumentNullException("username");
            }

            if (String.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException("password");
            }

            try
            {
                string hash  = Cryptographer.Hash(password);
                var query = from q in Context.Users
                            where q.Id == username && q.Password == hash
                            select q;

                return query.SingleOrDefault();
            }
            catch (Exception ex)
            {
                throw ExceptionFactory.Create<OException>(ex, ExceptionMessage.Failure, "authenticate user");
            }
        }

        /// <summary>
        /// Updates current password of specified username with a desired one.
        /// </summary>
        /// <param name="username">the username who wish to change the password</param>
        /// <param name="current">current password of the specified username</param>
        /// <param name="desired">the new password</param>
        /// <param name="who">user who initiates the change</param>
        /// <returns>true if password has been changed successfully</returns>
        public bool ChangePassword(string username, string current, string desired, User who)
        {
            if (String.IsNullOrEmpty(username))
            {
                throw new ArgumentNullException("username");
            }

            if (String.IsNullOrEmpty(current))
            {
                throw new ArgumentNullException("current");
            }

            if (String.IsNullOrEmpty(desired))
            {
                throw new ArgumentNullException("desired");
            }

            try
            {
                current = Cryptographer.Hash(current);

                // Retrieve current record for successful update using the same context
                var findUser = from u in Context.Users
                               where u.Id == username && u.Password == current
                               select u;
                UserData user = findUser.SingleOrDefault();

                user.Password  = Cryptographer.Hash(desired);
                user.UpdatedBy = who.Id;
                Context.SubmitChanges();
                return true;
            }
            catch (Exception ex)
            {
                throw ExceptionFactory.Create<OException>(ex, ExceptionMessage.Failure, "change password");
            }
        }

        /// <summary>
        /// Creates new user with the specified username and password.
        /// </summary>
        /// <param name="username">new user's id</param>
        /// <param name="password">new user's password</param>
        /// <param name="who">user who creates</param>
        /// <returns>user details that was created, else null</returns>
        public UserData NewUser(string username, string password, User who)
        {
            if (String.IsNullOrEmpty(username))
            {
                throw new ArgumentNullException("username");
            }

            if (String.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException("password");
            }

            if (who == null)
            {
                throw new ArgumentNullException("who");
            }

            try
            {
                UserData userData = new UserData();
                userData.Id        = username;
                userData.Password  = Cryptographer.Hash(password);
                userData.Name      = username.CapitaliseFirstLetter();
                userData.CreatedBy = who.Id;

                Context.Users.InsertOnSubmit(userData);
                Context.SubmitChanges();
                return userData;
            }
            catch (Exception ex)
            {
                throw ExceptionFactory.Create<OException>(ex, ExceptionMessage.Failure, "create new user");
            }
        }

        /// <summary>
        /// Clears and creates fresh list of users.
        /// </summary>
        /// <param name="userPasswords">pairs of user and password</param>
        /// <param name="creatorId">userid who initiates</param>
        /// <returns>list of created users</returns>
        public List<User> Setup(List<KeyValuePair<string, string>> userPasswords, string creatorId)
        {
            List<User> users = new List<User>();
            if (userPasswords == null || userPasswords.Count == 0)
            {
                return users;
            }
            if (String.IsNullOrEmpty(creatorId))
            {
                throw new ArgumentNullException("creatorId");
            }

            using (OContext context = Context)
            {
                using (TransactionScope transaction = new TransactionScope())
                {
                    string truncate = String.Format("truncate table [{0}]", (new UserData()).AttributeName<TableAttribute>());
                    context.ExecuteCommand(truncate);

                    foreach (KeyValuePair<string, string> userPassword in userPasswords)
                    {
                        string userid   = userPassword.Key;
                        string password = userPassword.Value;

                        UserData user = new UserData();
                        user.Id        = userid;
                        user.Password  = Cryptographer.Hash(password);
                        user.Name      = userid.CapitaliseFirstLetter();
                        user.CreatedBy = creatorId;

                        context.Users.InsertOnSubmit(user);
                        users.Add(user);
                    }

                    context.SubmitChanges();
                    transaction.Complete();
                    return users;
                }
            }
        }
    }
}
